﻿#ifndef WIN32
#include <unistd.h>
#endif // !WIN32
#include <string.h>
#include <stdio.h>
#include "Buf.h"
SBuf::SBuf(size_t size)
{
	_size = size;
	_b = _e = _base = new char[_size];
	memset(_base, 0, _size);
}
SBuf::SBuf()
{
	_size = 2048 * 10;
	_b = _e = _base = new char[_size];
	memset(_base, 0, _size);
}

SBuf::~SBuf(){
	if (_base){
		delete[] _base;
		_b = _e = _base=0;
	}
}
void SBuf::append(char* b, int32_t l)
{
	if (_e + l < _base + _size){
		memcpy(_e, b, l);
		_e += l;
	}
	else if (_e - _b + l <= _size){
		memmove(_base, _b, _e - _b);
		_e = _base + len();
		_b = _base;

		memcpy(_e, b, l);
		_e += l;
	}
	else{
		char* newbuf = new char[(_size + l) * 2];
		memset(newbuf, 0, l * 2);
		_size = (_size + l) * 2;
		int32_t len = _e - _b;
		memcpy(newbuf, _b, len);
		memcpy(newbuf + len, b, l);
		delete[] _base;
		_b = _base = newbuf;
		_e = _b + len + l;
	}
}

void SBuf::consume(int32_t l)
{
	if (l > (_e - _b))
	{
		_b = _e = _base;
	}
	else{
		_b += l;
	}
}
